package com.k4rthik.clipall.network.profile;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: k4rthik
 * Date: 4/6/12
 * Time: 10:59 AM
 */

public class ProfileManager
{
    private int activeProfileId;
    private int defaultProfileId;

    private int profileCounter = -1;
    private static List<Profile> registeredProfiles;

    private static ProfileManager INSTANCE = null;

    private ProfileManager()
    {
        registeredProfiles = new ArrayList<Profile>();
        createAndAddNewProfile();

        defaultProfileId = 0;
    }

    public static ProfileManager getInstance()
    {
        if(INSTANCE == null)
        {
            INSTANCE = new ProfileManager();
        }
        return INSTANCE;
    }

    public int getActiveProfileId()
    {
        return activeProfileId;
    }

    public void setActiveProfileId(int activeProfileId)
    {
        if(getProfileById(activeProfileId) != null) {
            this.activeProfileId = activeProfileId;
        }
    }

    public int getDefaultProfileId()
    {
        return defaultProfileId;
    }

    public void setDefaultProfileId(int defaultProfileId)
    {
        if(getProfileById(activeProfileId) != null) {
            this.defaultProfileId = defaultProfileId;
        }
    }

    public List<Profile> getRegisteredProfiles()
    {
        return registeredProfiles;
    }

    public Profile createAndAddNewProfile()
    {
        profileCounter++;

        Profile newProfile = new Profile(profileCounter, "Profile #"+profileCounter);
        activeProfileId = profileCounter;
        registeredProfiles.add(newProfile);

        return newProfile;
    }

    public int addConnectionToActiveProfile(UUID connectionId)
    {
        return addConnectionToProfile(connectionId, activeProfileId);
    }

    public int addConnectionToProfile(UUID connectionId, int profileId)
    {
        Profile thisProfile = getProfileById(profileId);
        if(thisProfile != null)
        {
            boolean addStatus = thisProfile.addConnection(connectionId);

            if(addStatus) {
                return 0;
            } else {
                return 1;
            }
        }

        return -1;
    }

    public Profile getProfileById(int profileId)
    {
        for(int i=0; i<registeredProfiles.size(); i++) {
            if(registeredProfiles.get(i).getProfileId() == profileId) {
                return registeredProfiles.get(i);
            }
        }

        return null;
    }
}
